package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Date;

@Service

public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>implements ApUserRealnameService {

    /**
     * 根据状态查询需要认证相关的用户信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1.检查参数
        if(dto==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.执行查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        if (dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(page, wrapper);
        //3.返回结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),(int)pageResult.getTotal(),pageResult.getRecords());
    }
    @Autowired
    ApUserMapper apUserMapper;
    /**
     * 认证用户
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult authPass(AuthDto dto, Short status) {
        //1.检查参数
        if (dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId,dto.getId())
                .eq(ApUserRealname::getStatus,1)
        );
        if (apUserRealname==null){
            CustException.cust(AppHttpCodeEnum.APUSERREALNAME_DATANOTEXIST_ERROR );
        }
        Integer apUserId = apUserRealname.getUserId();
        ApUser apUser=apUserMapper.selectOne(
                Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getId,apUserId)
                .eq(ApUser::getStatus,0)
        );
        if (apUser==null){
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST );
        }
        //3修改ApUserRealname状态
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotEmpty(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //4 如果 status 审核通知
        if (AdminConstants.PASS_AUTH.equals(status)){
            WmUser wmUser = createWmUser(dto, apUser);
            if (wmUser == null) {
                CustException.cust( AppHttpCodeEnum.WMUSER_ADD_ERROR );
            }

            //4.2 Feign创建 文章作者账号
            Boolean flag =  createApAuthor(wmUser);
            if (!flag) {
                CustException.cust( AppHttpCodeEnum.APAUTHOR_ADD_ERROR );
            }
        }
        //5修改apUser flag为自媒体人
        apUser.setFlag((short)1);
        apUserMapper.updateById(apUser);
        // 6返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Autowired
    ArticleFeign articleFeign;
    /**
     * 创建 文章作者的信息
     * @param wmUser
     * @return
     */
    private Boolean createApAuthor(WmUser wmUser) {
        //1 查询文章作者信息
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setWmUserId(wmUser.getId());
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setType(2);
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());
            ResponseResult result = articleFeign.save(apAuthor);
            // code=0
            if (result.getCode() == 0) {
                return true;
            }
        }
        return false;
    }

    @Autowired
    WemediaFeign wemediaFeign;
    /**
     * 创建 WmUser 自媒体账号
     * Tip: 自媒体用户的 账号和密码 默认规则是：和APP用户保存一致
     * @param dto
     * @param apUser
     * @return
     */
    private WmUser createWmUser(AuthDto dto, ApUser apUser) {

        //1 查询自媒体人
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUser.setType(0); // 个人
            wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

            wmUser = wemediaFeign.save(wmUser);

            if (wmUser.getId() != null) {
                return wmUser;
            }
        }
        return null;
    }
}
